<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { DnsNsListItem, DnsResolveDomainListItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import { cloneDeep, pick } from 'lodash-es'
import {
  addDnsAuthorityDomainApi,
  getDnsAuthorityDomainApi,
  getDnsAuthorityNameserversApi,
  updateDnsAuthorityDomainApi,
} from '@/apis/modules/dns'

interface IProp {
  record?: DnsResolveDomainListItem
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits<IEmits>()
interface IEmits {
  (e: 'reload', flag: boolean): void
}
const route = useRoute()
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive({
  name: '',
  ns_address_first: null,
  ns_address_second: null,
  remark: '',
})
const getTitle = computed(() => (props.record?.id ? '编辑域名' : '新建域名'))

const rules: Record<string, FieldRule> = {
  name: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('域名不能为空')
      }
      if (!regexpMap.domain.test(value)) {
        return callback('域名格式不正确')
      }
      callback()
    },
  },
  ns_address_first: { required: true, message: '请选择服务器地址' },
  ns_address_second: { required: true, message: '请选择服务器地址' },
}
const nsList = ref<DnsNsListItem[]>([])
const nsList2 = ref<DnsNsListItem[]>([])
const { run } = useListRequest(getDnsAuthorityNameserversApi, {
  afterFn(res: DnsNsListItem[]) {
    nsList.value = cloneDeep(res)
    nsList2.value = cloneDeep(res)
  },
  params: { limit: 500, offset: 0, order: 'desc', sort: 'created_at' },
})
function handleRefresh(type: 1 | 2) {
  if (type === 1) {
    formState.ns_address_first = undefined
    run()
  } else {
    formState.ns_address_second = undefined
    run()
  }
}
function handleJump() {
  window.open('/dns/ns-address?type=open', '_target')
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const data = {
    ...pick(formState, ['name', 'remark', 'id']),
    nameserver_ids: [formState.ns_address_first, formState.ns_address_second],
  }
  const apiPath = props.record?.id
    ? updateDnsAuthorityDomainApi
    : addDnsAuthorityDomainApi
  return apiPath(data).then(() => {
    Message.success('操作成功')
    visible.value = false
  })
}
async function getDetail() {
  await getDnsAuthorityDomainApi({
    id: props.record?.id,
    name: route.params.name,
  }).then((res) => {
    Object.assign(formState, { ...pick(res, ['id', 'name', 'remark']) })
    formState.ns_address_first = res.expected_nameservers[0].id
    formState.ns_address_second = res.expected_nameservers[1].id
  })
}
function handleOpen() {
  run()
  if (props.record?.id)
    getDetail()
}
function handleClose() {
  formRef.value?.resetFields()
  emit('reload', !!props.record?.id)
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="getTitle"
    :width="480"
    ok-text="保存"
    :mask-closable="false"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="域名"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          :max-length="255"
          show-word-limit
          :disabled="!!props.record?.id"
          placeholder="请输入域名"
        />
      </a-form-item>
      <a-form-item
        label="服务器地址一"
        field="ns_address_first"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.ns_address_first"
          show-footer-on-empty
          placeholder="请选择服务器地址"
        >
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建服务器地址</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
          <a-option
            v-for="ns in nsList"
            :key="ns.id"
            :value="ns.id"
            :disabled="formState.ns_address_second === ns.id"
          >
            {{ ns.hostname }}
          </a-option>
        </a-select>
        <a-button
          class="ml-2 shrink-0 text-color-1"
          type="outline"
          @click="handleRefresh(1)"
        >
          <template #icon>
            <i-icons-refresh />
          </template>
        </a-button>
      </a-form-item>
      <a-form-item
        label="服务器地址二"
        field="ns_address_second"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.ns_address_second"
          show-footer-on-empty
          placeholder="请选择服务器地址"
        >
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建服务器地址</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
          <a-option
            v-for="ns in nsList2"
            :key="ns.id"
            :value="ns.id"
            :disabled="formState.ns_address_first === ns.id"
          >
            {{ ns.hostname }}
          </a-option>
        </a-select>
        <a-button
          class="ml-2 shrink-0 text-color-1"
          type="outline"
          @click="handleRefresh(2)"
        >
          <template #icon>
            <i-icons-refresh />
          </template>
        </a-button>
      </a-form-item>
      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}
</style>
